#!/bin/bash

# 完整自动化部署脚本
# 服务器配置
SERVER_IP="106.75.5.247"
USERNAME="ubuntu"
PASSWORD="we13599793044"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${GREEN}🚀 开始自动化部署到云服务器: $SERVER_IP${NC}"

# 检查本地环境
echo -e "\n${BLUE}📋 检查本地环境...${NC}"

# 检查sshpass是否安装（Windows用户可能需要安装）
if ! command -v sshpass &> /dev/null; then
    echo -e "${YELLOW}⚠️  sshpass未安装，尝试安装...${NC}"
    if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
        # Windows Git Bash环境
        echo -e "${YELLOW}在Windows环境下，请手动安装sshpass或使用WSL${NC}"
        echo -e "${CYAN}继续使用expect方式...${NC}"
        USE_EXPECT=true
    else
        # Linux/Mac环境
        sudo apt-get update && sudo apt-get install -y sshpass || brew install sshpass
        USE_EXPECT=false
    fi
else
    USE_EXPECT=false
fi

# SSH函数
ssh_exec() {
    local command="$1"
    local description="$2"
    echo -e "${CYAN}⚡ $description${NC}"
    
    if [ "$USE_EXPECT" = true ]; then
        # 使用expect方式（适用于Windows）
        expect << EOF
spawn ssh -o StrictHostKeyChecking=no $USERNAME@$SERVER_IP "$command"
expect "password:"
send "$PASSWORD\r"
expect eof
EOF
    else
        # 使用sshpass（适用于Linux/Mac）
        sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no "$USERNAME@$SERVER_IP" "$command"
    fi
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ 完成: $description${NC}"
        return 0
    else
        echo -e "${RED}❌ 失败: $description${NC}"
        return 1
    fi
}

# 文件上传函数
upload_file() {
    local local_file="$1"
    local remote_file="$2"
    local description="$3"
    echo -e "${CYAN}📤 $description${NC}"
    
    if [ "$USE_EXPECT" = true ]; then
        expect << EOF
spawn scp -o StrictHostKeyChecking=no "$local_file" "$USERNAME@$SERVER_IP:$remote_file"
expect "password:"
send "$PASSWORD\r"
expect eof
EOF
    else
        sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no "$local_file" "$USERNAME@$SERVER_IP:$remote_file"
    fi
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ 上传完成: $description${NC}"
        return 0
    else
        echo -e "${RED}❌ 上传失败: $description${NC}"
        return 1
    fi
}

# 1. 测试连接
echo -e "\n${BLUE}🔗 测试服务器连接...${NC}"
ssh_exec "echo 'SSH连接正常' && uname -a" "测试SSH连接"
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 无法连接到服务器${NC}"
    exit 1
fi

# 2. 更新系统
echo -e "\n${BLUE}📦 更新系统并安装软件...${NC}"
ssh_exec "sudo apt update -y" "更新软件包列表"
ssh_exec "sudo DEBIAN_FRONTEND=noninteractive apt install -y openjdk-11-jdk tomcat9 tomcat9-admin nginx wget curl unzip expect" "安装必要软件"

# 3. 配置Java
echo -e "\n${BLUE}☕ 配置Java环境...${NC}"
ssh_exec "sudo update-alternatives --set java /usr/lib/jvm/java-11-openjdk-amd64/bin/java" "设置Java版本"
ssh_exec "java -version" "验证Java版本"

# 4. 检查并上传项目文件
echo -e "\n${BLUE}📤 上传项目文件...${NC}"
WAR_FILE="target/OrderStatsSystem-1.0-SNAPSHOT.war"
SQL_FILE="database_init_sqlite.sql"

if [ -f "$WAR_FILE" ]; then
    upload_file "$WAR_FILE" "/tmp/app.war" "上传WAR文件"
else
    echo -e "${RED}❌ WAR文件不存在: $WAR_FILE${NC}"
    echo -e "${YELLOW}请先运行: mvn clean package${NC}"
    exit 1
fi

if [ -f "$SQL_FILE" ]; then
    upload_file "$SQL_FILE" "/tmp/database_init.sql" "上传数据库脚本"
fi

# 5. 停止现有服务
echo -e "\n${BLUE}🛑 停止现有服务...${NC}"
ssh_exec "sudo systemctl stop tomcat9" "停止Tomcat服务"
ssh_exec "sudo systemctl stop nginx" "停止Nginx服务"

# 6. 部署应用
echo -e "\n${BLUE}🚀 部署应用...${NC}"
ssh_exec "sudo rm -rf /var/lib/tomcat9/webapps/ROOT*" "清理旧应用"
ssh_exec "sudo cp /tmp/app.war /var/lib/tomcat9/webapps/ROOT.war" "部署新应用"
ssh_exec "sudo chown tomcat:tomcat /var/lib/tomcat9/webapps/ROOT.war" "设置文件权限"

# 7. 配置Tomcat
echo -e "\n${BLUE}⚙️ 配置Tomcat...${NC}"
ssh_exec "echo 'export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64' | sudo tee /etc/default/tomcat9" "配置Java路径"
ssh_exec "echo 'export CATALINA_OPTS=\"-Xmx2048m -Xms1024m -XX:+UseG1GC\"' | sudo tee -a /etc/default/tomcat9" "配置JVM参数"

# 8. 配置Nginx反向代理
echo -e "\n${BLUE}🌐 配置Nginx反向代理...${NC}"
ssh_exec "sudo tee /etc/nginx/sites-available/default > /dev/null << 'EOF'
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    
    server_name _;
    
    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_connect_timeout 30;
        proxy_send_timeout 30;
        proxy_read_timeout 30;
    }
    
    # 静态文件缓存
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
        proxy_pass http://localhost:8080;
        proxy_cache_valid 200 1d;
        add_header Cache-Control \"public, immutable\";
    }
}
EOF" "创建Nginx配置文件"

ssh_exec "sudo nginx -t" "测试Nginx配置"

# 9. 配置防火墙
echo -e "\n${BLUE}🔥 配置防火墙...${NC}"
ssh_exec "sudo ufw allow OpenSSH" "允许SSH访问"
ssh_exec "sudo ufw allow 80/tcp" "开放HTTP端口"
ssh_exec "sudo ufw allow 8080/tcp" "开放Tomcat端口"
ssh_exec "sudo ufw --force enable" "启用防火墙"

# 10. 启动服务
echo -e "\n${BLUE}🔧 启动服务...${NC}"
ssh_exec "sudo systemctl start tomcat9" "启动Tomcat"
ssh_exec "sudo systemctl enable tomcat9" "设置Tomcat开机启动"
ssh_exec "sudo systemctl start nginx" "启动Nginx"
ssh_exec "sudo systemctl enable nginx" "设置Nginx开机启动"

# 11. 等待服务启动
echo -e "\n${YELLOW}⏳ 等待服务启动...${NC}"
sleep 45

# 12. 检查服务状态
echo -e "\n${BLUE}🔍 检查服务状态...${NC}"
ssh_exec "sudo systemctl is-active tomcat9" "检查Tomcat状态"
ssh_exec "sudo systemctl is-active nginx" "检查Nginx状态"
ssh_exec "sudo netstat -tlnp | grep :8080" "检查8080端口"
ssh_exec "sudo netstat -tlnp | grep :80" "检查80端口"

# 13. 测试访问
echo -e "\n${BLUE}🎯 测试访问...${NC}"
ssh_exec "curl -I http://localhost:8080 || echo 'Tomcat未响应'" "测试Tomcat直接访问"
ssh_exec "curl -I http://localhost || echo 'Nginx未响应'" "测试Nginx代理访问"

# 14. 查看日志（最后几行）
echo -e "\n${BLUE}📋 查看服务日志...${NC}"
ssh_exec "sudo journalctl -u tomcat9 --no-pager -l -n 10" "查看Tomcat日志"
ssh_exec "sudo journalctl -u nginx --no-pager -l -n 5" "查看Nginx日志"

# 15. 创建数据库
echo -e "\n${BLUE}🗄️ 初始化数据库...${NC}"
ssh_exec "mkdir -p /home/ubuntu/app-data" "创建应用数据目录"
if [ -f "$SQL_FILE" ]; then
    ssh_exec "sqlite3 /home/ubuntu/app-data/orders.db < /tmp/database_init.sql" "初始化SQLite数据库"
fi

# 完成
echo -e "\n${GREEN}🎉 部署完成！${NC}"
echo -e "${YELLOW}📱 访问地址：${NC}"
echo -e "   ${CYAN}• Nginx代理访问: ${NC}http://$SERVER_IP"
echo -e "   ${CYAN}• Tomcat直接访问: ${NC}http://$SERVER_IP:8080"
echo -e "${YELLOW}💡 默认登录账号: ${NC}admin / admin123"
echo -e "${YELLOW}📊 系统监控: ${NC}"
echo -e "   ${CYAN}• 查看Tomcat日志: ${NC}sudo journalctl -u tomcat9 -f"
echo -e "   ${CYAN}• 查看Nginx日志: ${NC}sudo tail -f /var/log/nginx/access.log"
echo -e "   ${CYAN}• 重启应用: ${NC}sudo systemctl restart tomcat9"

echo -e "\n${GREEN}✨ 大数据订单统计与推荐系统部署成功！${NC}" 